package com.MonkWorks.timedormitory;

import java.util.Iterator;
import java.util.List;

import com.MonkWorks.clockDTO.User;
import com.MonkWorks.timedormitoryDB.ItimeProvider;
import com.MonkWorks.timedormitoryDB.TimeDB;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;


public class EditUserActivity extends Activity {

	private Spinner UserSelect;
	private EditText Password;
	private EditText FirstName;
	private EditText LastName;
	private EditText Email;
	private Button EditSave;
	private Button Back;
	private String UserValue;
	private String dbFirstName;
	private String dbLastName;
	private String dbEmail;
	private String dbPass;
	ItimeProvider timeDB;
	String test = "test";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_user);
		initComponents();
		
	}

	private void initComponents() {
		timeDB = new TimeDB(this);
		Password = (EditText) findViewById(R.id.editPassword);
		FirstName = (EditText) findViewById(R.id.editFirstName);
		LastName = (EditText) findViewById(R.id.editLastName);
		Email = (EditText) findViewById(R.id.editEmail);
		UserSelect = (Spinner) findViewById(R.id.UserSelect);
		
		
		//initiate the spinner
		List<String> fetchUser;
		try {
			fetchUser = timeDB.fetchAllUsers();
			Log.i("EditUserActivity", "fetchUser for Spinner");
			ArrayAdapter userAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_dropdown_item_1line, fetchUser);

			// finalize the values that go into the spinner
			UserSelect.setAdapter(userAdapter);

		} catch (Exception e) {
			popup("unable to populate spinner");
			Log.e("PunchActivity", "FetchJob");
		}
		UserSelect.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				UserValue = UserSelect.getSelectedItem().toString();
				UserInfo();
				try {
					//load text fields with info corresponding to the user
					loadInfo();
				} catch (Exception e) {
					Log.e("UserInfo()", "Cannot retrive user");
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				UserValue = "Admin";

			}

		});
		
		//push the edit values
		EditSave = (Button) findViewById(R.id.btnSave);
		EditSave.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//call the update user method
				try {
					//put textInput values to variables
					String newPass = Password.getText().toString();
					String newfirstN = FirstName.getText().toString();
					String newlastN = LastName.getText().toString();
					String newEmail = Email.getText().toString();
					//check to see if they are empty else use original value from user
					if(!newPass.isEmpty())
					{
						dbPass = newPass;
					}
					if(!newfirstN.isEmpty())
					{
						dbFirstName = newfirstN;
					}
					if(!newlastN.isEmpty())
					{
						dbLastName = newlastN;
					}
					if(!newEmail.isEmpty())
					{
						dbEmail = newEmail;
					}
					//call on the method to update user
					timeDB.updateUser(UserValue, dbPass, dbFirstName, dbLastName, dbEmail);
					//output a popup to say that the user has been updated and clear all fields
					popup("USER UPDATED");
					loadInfo();
					Log.d("EditUser", "Updated User");
					
				} catch (Exception e) {
					Log.e("EditUser", "Cannot Update User");
					popup("Cannot Update User");
				}
				
			}
		});
		Back = (Button) findViewById(R.id.btnBack);
		Back.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent BackIntent = new Intent(v.getContext(), AdminToolsActivity.class);
				startActivityForResult(BackIntent, 0);
			}
		});
		
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_edit_user, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    
	      //Logs the user out
	      if (item.getItemId() == R.id.Logoff) {
	    	  
	    	  Intent  MIntent = new Intent(getBaseContext(),LoginActivity.class);
				startActivityForResult(MIntent, 0);
				popup("You have logged out");
	        return true;
	      }


	      return (super.onOptionsItemSelected(item));
	    }
	
	public void UserInfo() {
		try {
			// call method to find user by username
			User currentUser = timeDB.fetchUserByUsername(UserValue);
			dbFirstName = currentUser.getFirstName();
			dbLastName = currentUser.getLastName();
			dbEmail = currentUser.getemail();
			dbPass = currentUser.getPassword();
		} catch (Exception e) {
			Log.e("UserInfo()", "Cannot retrive user");
			e.printStackTrace();
		}
	}
	private void loadInfo(){
		//load text fields with info corresponding to the user
		try {
			User currentUser = timeDB.fetchUserByUsername(UserValue);
			FirstName.setText(dbFirstName);
			LastName.setText(dbLastName);
			Email.setText(dbEmail);
			Password.setText(dbPass);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	protected void popup(String message) {
		// this is how we make a popup.
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}

}
